//
//  CLLMainViewController.swift
//  CLWeiNo
//
//  Created by DDC on 2017/10/10.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

/// 主控制器
class CLLMainViewController: UITabBarController {

    // MARK:  - 私有控件
    fileprivate lazy var composeButton:UIButton = UIButton.hm_button(withImageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 新特性
        setUpNewFeature()
        
        // 创建控制器
        setUpChildControllers()
        // 撰写按钮
        setUpComposeButton()
        
        // 设置代理
        delegate = self
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(logonClickNotification), name: NSNotification.Name(rawValue: CLLWBUserShouldLogonNotification), object: nil)
    }
    // MARK:  - 通知按钮实现方法
    @objc func logonClickNotification(n:Notification){
        
        print("登录的通知按钮方法")
        let vc = UINavigationController(rootViewController: CLLOAuthViewController())
        present(vc, animated: true, completion: nil)
    }
    // MARK:  - 撰写按钮点击事件
    @objc fileprivate func composeButtonClick(){
        print("撰写按钮")
        let v = CLLComposeView.composeView()
        // 显示
       v.show { (clsName) in
        
        // 通过文件名 获得控制器类型
        guard let clsName = clsName,
              let cls = NSClassFromString(Bundle.main.namespace() + "." + clsName) as? UIViewController.Type
            else {
            return
        }
        let vc = cls.init()
        // 导航栏控制器
        let nav = UINavigationController(rootViewController: vc)
        self.present(nav, animated: true, completion: { 

            
        })
        
        }

    }

}

// MARK: - 创建控制器
extension CLLMainViewController {
    
    /// 设置撰写按钮
    func setUpComposeButton() {
        // 添加撰写按钮
        tabBar.addSubview(composeButton)
        // 设置frame
        let count = CGFloat(childViewControllers.count)
        // 盖住控制器的容错点，增大tabbar的宽度
        let w = tabBar.bounds.width / count - 1
        
        composeButton.frame = tabBar.bounds.insetBy(dx: w * 2, dy:0)
        
        // 撰写按钮添加点击事件
        composeButton.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
    }
    /// 设置子控制器
    func setUpChildControllers() {
        
        // 设置控制器所需要的字典数组
        let array = [
            ["clsName":"CLLHomeViewController","title":"首页","imgName":"home",
             "visitorInfo":["imageName":"","tipString":"哈哈"]],
            ["clsName":"CLLDiscoveryViewController","title":"发现","imgName":"discover",
                "visitorInfo":["imageName":"visitordiscover_image_message","tipString":"哈哈"]],
            ["clsName":"UIViewController"],
            ["clsName":"CLLMessageViewController","title":"消息","imgName":"message_center",
             "visitorInfo":["imageName":"visitordiscover_image_message","tipString":"哈哈"]],
            ["clsName":"CLLProfileViewController","title":"我的","imgName":"profile",
             "visitorInfo":["imageName":"visitordiscover_image_profile","tipString":"我的"]]
                   ]
        // 将数组写入json文件
//        (array as NSArray).write(toFile: "/Users/DDC/Desktop/main.json", atomically: true)
        // 定义可变数组
        var arrayM = [UIViewController]()
        for dict in array {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }
    
    func controller(dict:[String:Any])->UIViewController {
        
        // 守护创建分支控制器的条件
        guard let clsName = dict["clsName"] as? String,
              let title = dict["title"] as? String,
              let imgName = dict["imgName"] as? String,
              let cls = NSClassFromString(Bundle.main.namespace() + "." + clsName) as? CLLBaseViewController.Type,
              let visitorDict = dict["visitorInfo"] as? [String:String]
            else {
                return UIViewController()
        }
        // 创造视图控制器
        let vc = cls.init()
        // 设置控制器的字典赋值
        vc.visitorInfoDict = visitorDict
        // 设置标题
        vc.title = title
        // 设置tabbar素材
        vc.tabBarItem.image = UIImage(named:"tabbar_"+imgName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imgName+"_highlighted")?.withRenderingMode(.alwaysOriginal)
        // 设置tabbar字体
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
        let nav = CLLNavigationController(rootViewController: vc)
        
        return nav
    }
}
// MARK: - 设置横屏设置
extension CLLMainViewController {
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
}
// MARK: - UITabBarControllerDelegate
extension CLLMainViewController:UITabBarControllerDelegate {
    
    /// 实现点击tabbar跳转控制器的方法
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        // 获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        // 判断当前控制器的索引是首页,并且idx也是首页的索引
        if selectedIndex == 0 && idx == selectedIndex {
            
            print("点击了首页")
            // 让表格滚动到顶部
            // 获取表格控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! CLLHomeViewController
            // 滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0 ,y: 64), animated: true)
            
            // 异步刷新表格数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
            
                vc.loadData()
            })
        }
        return !viewController.isMember(of: UIViewController.self)
    }
    
    
}

// MARK: - 新特性以及欢迎界面处理
extension CLLMainViewController {
 
    fileprivate func setUpNewFeature(){
        /// 设置是否是新特性界面显示
        let v = isNewFeature ? CLLNewFeatureView.newFeature() : CLLWelcomeView.welcomeView()
        if isNewFeature {
            // 提示更新
            let alertView = UIAlertView(title: "更新", message: "发现了新的版本", delegate: self as? UIAlertViewDelegate, cancelButtonTitle: "cancel", otherButtonTitles: "确定")
            alertView.show()
        }
        v.frame = view.bounds
        
        view.addSubview(v)
    }
    // 新特性属性
    fileprivate var isNewFeature:Bool  {
        // 根据当前版本号与保存在沙盒中的版本号来进行比较是否显示新特性界面
        //CFBundleShortVersionString
        // 1.取出当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
        // 2.取保存在Document中[iTunes备份](存储在偏好中)的版本号
        let filePath:String = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last as NSString?)?.appendingPathComponent("versionNumber"))!
        let systemVersion = (try? String.init(contentsOfFile: filePath)) ?? ""
        // 3.保存当前版本号到偏好中
        try? currentVersion?.write(toFile: filePath, atomically: true, encoding: .utf8)
        // 4.返回两个版本号是否一致
        return currentVersion != systemVersion
    }
}






















